package cn.zooz.admin.config.shiro;

import cn.zooz.entity.SysUser;
import cn.zooz.manager.sys.SysUserManager;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.google.common.collect.ImmutableSet;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.builder.ReflectionToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import javax.annotation.Resource;

/**
 * Created by Bradish7Y on 2017/9/8.
 */
@Slf4j
public class ZoozShiroRealm extends AuthorizingRealm {
    @Override
    public void setName(String name) {
        super.setName("ZoozShiroRealm");
    }

    /**
     * 权限验证
     *
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setRoles(ImmutableSet.<String>of("admin"));
        info.addStringPermission("menu:update:*");
        info.addStringPermission("menu:delete:1");

        log.info("授权：" + ReflectionToStringBuilder.toString(info, ToStringStyle.MULTI_LINE_STYLE));

        return info;
    }

    /**
     * 认证
     *
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;

        log.info("验证当前Subject时获取到token为：" + ReflectionToStringBuilder.toString(token, ToStringStyle.MULTI_LINE_STYLE));

        //查出是否有此用户
        SysUser user = sysUserManager.selectOne(new EntityWrapper<SysUser>().eq("username", token.getUsername()));
        if (user != null) {
            // 若存在，将此用户存放到登录认证info中，无需自己做密码对比，Shiro会为我们进行密码对比校验
            SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user.getUsername(), user.getPassword(), getName());
            //ByteSource没有实现Serializable接口
            info.setCredentialsSalt(ByteSource.Util.bytes(user.getPasswordSalt()));

            return info;
        }
        return null;
    }

    @Resource
    public SysUserManager sysUserManager;

}
